<template>
  <div class="Messages" v-if="isRedoal">
    <div class="topheader">
    </div>
    <div class="allmain">
      <div class="main_title">{{ activity.title }}</div>
      <div class="main_time">开始时间:{{ startTime }}</div>
      <div class="ql-editor" v-html="activity.content">
      </div>
      <div class="main_time">结束时间:{{ endTime }}</div>
    </div>
    <div class="but">
      <el-button
        type="warning"
        class="tijiao"
        @click="show = true"
        v-if="aCstatue == 0"
        >立即报名</el-button
      >
      <el-button
        type="warning"
        @click="SignUpSign"
        v-if="aCstatue == 1 && activity.type == 1"
        class="tijiao"
        >线下签到</el-button
      >
      <el-button
        type="warning"
        @click="signRequest($route.query.row)"
        v-if="aCstatue == 1 && activity.type == 0"
        class="tijiao"
        >线上签到</el-button
      >
      <el-button
        type="warning"
        @click="SignUp"
        v-if="aCstatue == 2"
        class="tijiao"
        >打卡</el-button
      >
      <el-button type="info" v-if="aCstatue == 3">活动已结束</el-button>
      <el-button type="info" v-if="aCstatue == 4">已完成</el-button>
    </div>
    <div class="color_i" v-if="aCstatue == 4 && activity.used==1" @click="toJumpDraw">
      <i class="el-icon-guide"></i>立即抽奖
    </div>
   <!-- <div
      style="
        position: fixed;
        z-index: 1;
        min-height: 100vh;
        width: 100vw;
        top: 0;
        left: 0;
        background-color: white;
        opacity: 0.55;
      "
      @click="showPic"
      v-show="diaIsShow"
    ></div> -->
    <div
      style="
        position: fixed;
        top: 25vh;
        height: calc(80vw * 1.5);
        width: 80vw;
        margin-left: 10vw;
        padding-top: 10px;
        border-radius: 25px;
        border: 2px solid #73ad21;
        background-color: white;
        text-align: center;
        z-index: 2;
        box-shadow: 10px 10px 5px #888888;
      "
      v-show="diaIsShow"
    >
      长按图片保存海报
      <div
        ref="imageTofile"
        :style="{
          height: 'calc(70vw*1.5)',
          width: '70vw',
          overflow: 'hidden',
          'margin-left': '5vw',
        }"
        v-show="isShow"
      >
        <img
          style="
            height: calc(70vw * 1.5);
            width: 70vw;
            position: absolute;
            left: 5vw;
          "
          :src="backgroundBase64"
        />
        <img
          style="
            height: calc(70vw * 0.25);
            width: calc(70vw * 0.25);
            margin: calc(80vw * 0.875) -10vw;
            position: absolute;
            z-index: 999;
          "
          :src="QRcodeBase64"
        />
      </div>

      <img
        :style="{
          height: 'calc(70vw*1.5)',
          width: '70vw',
        }"
        :src="outUrl"
        v-show="!isShow"
      />
    </div>
    <!-- 填写信息 -->
    <van-popup v-model="show" class="naire-content">
      <div class="txxx">填写信息</div>
      <van-form @submit="onSubmit">
        <van-field
          v-model="username"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="phone"
          type="text"
          name="手机号"
          label="手机号"
          maxlength="11"
          placeholder="手机号"
          :rules="[{ required: false, message: '请填写手机号' }]"
        />
        <van-field
          class="beizhu"
          v-model="remarks"
          rows="1"
          autosize
          label="备注"
          type="textarea"
		  maxlength="12"
          placeholder="请输入备注"
          show-word-limit
        />
        <div style="margin-top: 46px">
          <van-button
            round
            block
            type="warning"
            native-type="submit"
            style="background-color: orange"
            >提交</van-button
          >
        </div>
      </van-form>
    </van-popup>
    <!-- //提示框 -->
    <el-dialog
      title=""
      :visible.sync="centerDialogVisible"
      width="90%"
      center
      :append-to-body="true"
    >
      <div class="img_all">
        <el-upload
          class="avatar-uploader"
          :action=baseuUrl
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handSess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
        <van-field
          v-model="content"
          class="beizhu"
          rows="2"
          autosize
          label="留言"
          type="textarea"
          placeholder="请输入留言"
          show-word-limit
        />
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="warning" class="tijiao" @click="addLL">上传</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import html2canvas from "html2canvas";
import { MessageBox, Toast } from "mint-ui";
import request from "@/utils/request";
import wx from "weixin-js-sdk";
import {server} from "@/utils/env";
export default {
  name: "SystemMessages",
  inject: ["reload"],
  data() {
    return {
      centerDialogVisible: false,
      imgs: [],
      activity: {},
      aCstatue: null,
      multiple: true,
      dialogImageUrl: "",
      dialogVisible: false,
      imgList: [],
      // 生成图片
      backgroundBase64: "",
      QRcodeBase64: "",
      outUrl: "",
      isShow: true,
      diaIsShow: false,
      sumLL: null,
      // dialog_visible: false,
      startTime: "",
      endTime: "",
      username: "",
      phone: "",
      show: false,
	  remarks:'',
	  content:'',
	  isRedoal:false,
	  isFirst:window.sessionStorage.getItem('first'),
    baseuUrl:'',
	drawType:''
    };
  },
  created() {
    let userId=window.localStorage.getItem('userId')
    if(this.$route.params.time){
    	window.location.reload() 
    }else{
		this.isRedoal=true
    }
    this.baseuUrl=server.baseURL+"/generator/upload/front/upload"
    this.updataLIST();
    // this.getImage();
	
		},
		methods: {
    GetQueryString(name) {
      var reg = new RegExp("\\b" + name + "=([^&]*)");
      var r = location.href.match(reg);
      if (r != null) return decodeURIComponent(r[1]);
    },
    back() {
      this.$router.go(-1); //返回上一层
    },
    SignUp() {
      console.log("立即报名");
      this.centerDialogVisible = true;
    },

    updataLIST() {
      let query = {
        activityId: this.$route.query.row,
      };
      request({
        url: "/generator/activity/front/info",
        method: "get",
        params: query,
      }).then((response) => {
        console.log(response.activity);
        this.startTime = response.activity.startTime.substr(0, 10);
        this.endTime = response.activity.endTime.substr(0, 10);
		let _img=response.activity.content.replace(/<img/g, '<img style="max-width: 100%;" ')
		response.activity.content=_img
		console.log(_img,response.activity.content)
        this.activity = response.activity;
        this.aCstatue = response.status;
		this.drawType=response.type
      });
    },
    onSubmit() {
      console.log("立即报名");
      let data = {
        activityId: this.$route.query.row,
        truename: this.username,
        phone: this.phone,
        remarks: this.remarks,
      };
      request({
        url: "/generator/activity/front/join",
        method: "post",
        data: data,
      }).then((response) => {
        console.log(response.message);
        this.show = false;
        if (response.message == "报名成功") {
          Toast(response.message);
          this.reload();
        } else {
          Toast(response.message);
        }
        setTimeout(() => {
          if (this.isFirst == 0) {
            this.$router.replace({ name: "jumpGZH" });
          }
        }, 1000);
      });
    },

    // 签到接口
    signRequest(id) {
      if (id != this.$route.query.row) {
        Toast("请扫描正确二维码！");
        return;
      }
      let query = {
        activityId: this.$route.query.row,
      };
      request({
        url: "/generator/activity/front/register",
        method: "get",
        params: query,
      }).then((response) => {
        console.log(response.message);
        if (response.message == "签到成功") {
          Toast(response.message);
          setTimeout(() => {
            this.reload();
          }, 1000);
        } else {
          Toast(response.message);
        }
      });
    },
    // 线上签到
    lineSign(id) {},
    // 签到扫码
    SignUpSign() {
      var local = location.href.split("#")[0]; // 获取页面url
      request({
        url: "generator/user/front/sign",
        method: "post",
        data: {
          url: local,
        },
      }).then((res) => {
        localStorage.setItem("jsapi_ticket", res.jsapi_ticket);
        //拿到后端给的这些数据
        let timestamp = res.timestamp;
        let nonceStr = res.nocestr;
        let signature = res.signature;
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: server.appId, // 必填，公众号的唯一标识，填自己的！
          timestamp: timestamp, // 必填，生成签名的时间戳，刚才接口拿到的数据
          nonceStr: nonceStr, // 必填，生成签名的随机串
          signature: signature, // 必填，签名，见附录1
          jsApiList: ["checkJsApi", "scanQRCode"],
        });

        wx.ready(() => {
          wx.checkJsApi({
            jsApiList: ["scanQRCode"],
            success: (res) => {
              console.log(this);
              wx.scanQRCode({
                needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
                success: (res) => {
                  var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                  this.signRequest(res.resultStr);
                },
              });
            },
          });
        });

        wx.error(function (res) {
          Toast("扫一扫调用失败,刷新再试一次吧！")
        });
      });
    },
    uploadFile(file) {
      this.formDate.append("file", file.file);
      console.log(file, this.formDate);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      console.log(file);
      this.dialogVisible = true;
    },
    handSess(file) {
      console.log(file);
      let imgList = this.imgList;
      let index = imgList.length;
      let arr = file.url;
      this.imgList.push(arr);
      console.log(this.imgList);
      // if (this.imgList.length == 3) {
      // this.dialog_visible=true
      // } else {
      // this.dialog_visible=false
      // }
    },
    addLL() {
      let query = {
        activityId: this.$route.query.row,
        image: this.imgList.toString(),
        content: this.content,
      };
      request({
        url: "/generator/activity/front/clock",
        method: "post",
        data: query,
      }).then((response) => {
        console.log(response.message);
        Toast(response.message);
        this.reload();
        // alert(JSON.stringify(response.token));
        this.centerDialogVisible = false;
      });
    },
    getImage() {
      console.log("生成海报");
      let query = { userId: 1, page: "jifen" };
      request({
        url: "/generator/poster/front/poster",
        method: "get",
        params: query,
      }).then((response) => {
        this.backgroundBase64 =
          "data:image/png;base64," + response.poster.backPic;
        this.QRcodeBase64 = "data:image/png;base64," + response.qrcode;
        // setTimeout(()=>this.toImage(), 100);
      });
    },
	// 特殊活动跳转抽奖
	toJumpDraw(){
		let userId=window.localStorage.getItem('userId')
		if(this.aCstatue==4){
			if (this.drawType==0) {
			  this.$router.push({ name: "turntable", query: { row: this.activity.drawId ,shareUserId:userId,form:'ans'},	params:{time:new Date().getTime()} });
			} else if (this.drawType==1) {
			  this.$router.push({ name: "draw", query: { row: this.activity.drawId,shareUserId:userId ,form:'ans'} ,	params:{time:new Date().getTime()}});
			}
		}
		  
	},
    showPic() {
      this.diaIsShow = !this.diaIsShow;
      // this.getImage();
      this.backgroundBase64;
      this.QRcodeBase64;
      if (this.diaIsShow) {
        this.getNummo();
        setTimeout(() => this.toImage(), 100);
      } else {
        this.isShow = true;
      }
    },
    getNummo() {
      request({
        url: "/generator/poster/front/posterPoint",
        method: "get",
      }).then((response) => {
        console.log(response);
      });
    },
    toImage() {
      // TODO开始生成
      // 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等
      html2canvas(this.$refs.imageTofile, {
        backgroundColor: null,
      }).then((canvas) => {
        // TODO结束生成
        let url = canvas.toDataURL("image/png");
        this.outUrl = url;
        console.log(this.outUrl);
        if (this.outUrl) {
          this.isShow = false;
        }
      });
    },
  },
};
</script>

<style scoped>
	.van-field__value{
		overflow: hidden;
		height: 50px;
	}
.Messages {
  min-height: 100vh;
}
.topheader {
  width: 100%;
  background-color: black;
}
.Theadermain {
  height: 48px;
  display: flex;
  justify-content: space-between;
  color: #fff;
  align-items: center;
  width: 95%;
  margin: 0 auto;
}
.headerimg {
  width: 0.8rem;
  margin-left: 10px;
  transform: rotate(180deg);
}
.allmain {
  padding: 20px;
}
.main_title {
  font-weight: bold;
}
.main_time {
  padding: 20px 0;
  color: #b6bfd0;
}
.main_titleP {
  text-indent: 2em;
}
.main_tImg {
  /* border: 1px solid red; */
  display: flex;
  justify-content: center;
  margin: 10px 0;
}
.but {
  /* border: 1px solid red;  */
  text-align: center;
}
.float_left {
  float: left;
}

.add_upload .add_upload_button {
  position: relative;
  width: 12rem;
  height: 12rem;
  border: none;
  background: rgb(236, 236, 236);
}
.add_upload .add_upload_icon {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
.add_upload .add_upload_file {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  font-size: 0;
}

.add_upload_imgBox .add_upload_imgDiv {
  position: relative;
  width: 12rem;
  height: 12rem;
  margin: 0 0.1rem 0.1rem 0;
}
.add_upload_imgBox .add_upload_imgDiv img {
  width: 100%;
  height: 100%;
}
.add_upload_imgBox .add_upload_close {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.add_upload_imgBox .add_upload_close img {
  width: 100%;
  height: 100%;
}
.img_all {
  /* border: 1px solid red; */
  margin-bottom: 50px;
}
.color_i {
  color: #f6a15d;
  padding-top: 50px;
  text-align: center;
}
.naire-content {
  width: 80%;
  height: 55%;
    padding: 20px 24px 20px 24px;
  border-radius: 10px;
  border: #f8f8f8 solid 1px;
  box-shadow: #989898 4px 4px 7px -4px;
}
.tijiao {
  color: #fff;
  background-color: orange !important;
  border: none !important;
  min-width: 150px !important;
  border-radius: 30px !important;
}
.shangchuan {
  color: #fff;
  background-color: orange !important;
  border: none !important;
  border-radius: 30px !important;
}
.el-upload-list--picture-card .el-upload-list__item {
  width: 85px !important;
  height: 85px !important;
}
.beizhu {
  /* overflow-y: auto !important; */
  height: 80px !important;
}
.txxx{
  width: 100%;
  text-align: center;
  font-size: 18px;
  margin-bottom: 10px;
}
</style>